package com.gugee.ins.data.analysis.service.impl;

import com.gugee.common.thread.ScheduleTemplate;

import com.gugee.ins.common.constant.InsBloggerMsgTypeCodeEnum;
import com.gugee.ins.common.dal.ai.AiAnalysisClient;
import com.gugee.ins.common.dal.service.blogger.InsBloggerDao;
import com.gugee.ins.common.dal.service.blogger.InsBloggerMainDao;
import com.gugee.ins.common.model.ai.InComeRequest;
import com.gugee.ins.common.model.ai.InComeResponse;
import com.gugee.ins.data.analysis.config.InsAnalysisConfig;
import com.gugee.ins.data.analysis.service.InsAnalysisIncomeService;
import com.gugee.ins.data.common.msg.InsBloggerMessage;
import com.xiguaji.boot.toolkit.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

/**
 * InsAnalysisInComeService 服务
 * @author Huangxin
 */
@Slf4j
@Service
public class InsAnalysisIncomeServiceImpl implements InsAnalysisIncomeService {

    /**
     * 配置
     */
    @Autowired
    InsAnalysisConfig insAnalysisConfig;

    /**
     * 线程调度
     */
    @Autowired
    ScheduleTemplate scheduleTemplate;

    /**
     * ai
     */
    @Autowired
    AiAnalysisClient aiAnalysisClient;

    /**
     * InsBloggerDao
     */
    @Autowired
    InsBloggerDao insBloggerDao;

    /**
     * InsBloggerDao
     */
    @Autowired
    InsBloggerMainDao insBloggerMainDao;

    /**
     * kafkaTemplate
     */
    @Autowired
    KafkaTemplate<Long,InsBloggerMessage> kafkaTemplateInsAnalysisAvatar;

    /**
     * 线程池
     */
    ForkJoinPool forkJoinPool;

    /**
     * 线程名
     */
    private String workName = "insAnalysisIncome-worker";

    /**
     * 初始化线程池
     */
    @PostConstruct
    public void init() {
        forkJoinPool = ThreadPoolUtils.forkJoinPool(insAnalysisConfig.getInsAnalysisIncomeCorePollSize(), workName);
        scheduleTemplate.attach(workName, forkJoinPool);
    }

    /**
     * 处理 分析收入 任务
     * @param insBloggerMessages
     */
    @Override
    public void handleAnalysisIncome(List<InsBloggerMessage> insBloggerMessages) {
        try {
            forkJoinPool.submit(() -> insBloggerMessages.parallelStream().forEach(msg -> {
                try {
                    // 分析收入
                    analysisIncome(msg);
                } catch (Exception ex) {
                    log.error("insAnalysisIncome error. uid:{}, error :{}" ,
                            msg.getUid(),ex.getMessage());
                }
            })).get();
        } catch (Exception ex) {
            log.error("insAnalysisIncome thread error.  {}" ,  ex.getMessage());
        }
    }

    /**
     * 分析收入
     *
     * @param insBloggerMessage
     */
    public void analysisIncome(InsBloggerMessage insBloggerMessage){
        long start = System.currentTimeMillis();
        long uid = insBloggerMessage.getUid();

        // 判断是否需要处理
        if(insBloggerMessage.getTypeCode() != InsBloggerMsgTypeCodeEnum.NO_HANDLE_AND_DO_OTHER_OPT.getCode()){
            try{
                List<InComeRequest> inComeRequest = insBloggerMainDao.findMInsAnalysisIncomeByUid(uid);
                analysisIncome(inComeRequest);
            }catch (Exception e){
                log.error(" insMainBlogger insAnalysisIncome error. uid:{}, error :{}",uid,e.getMessage());
            }
        }
        long limitTime = start / 1000 - insAnalysisConfig.getInsAnalysisIncomeIntervalDay() * 24 * 3600;
        // 查询他的活跃粉丝且发送
        List<InComeRequest> subMessages = insBloggerMainDao.findInsAnalysisIncomeByUid(uid,limitTime);
        if(subMessages != null && !subMessages.isEmpty() && insAnalysisConfig.getInsAnalysisIncomeCount() > 0){
            for(int i = 0,j = insAnalysisConfig.getInsAnalysisIncomeCount(); i < subMessages.size();){
                if(j > subMessages.size()){
                    j = subMessages.size();
                }
                analysisIncome(subMessages.subList(i,j));
                i = j;
                j += insAnalysisConfig.getInsAnalysisIncomeCount();
            }

            // 发送优先统计的消息
            sendPriorityStMsg(insBloggerMessage);
        }

        if ((System.currentTimeMillis() - start) / 1000 > insAnalysisConfig.getInsAnalysisIncomeDebugTimeLimit()) {
            log.info("insAnalysisIncome uid:{} use time:{}s", uid,(System.currentTimeMillis() - start) / 1000);
        }
    }

    /**
     * 分析收入
     * @param inComeRequests
     */
    public void analysisIncome(List<InComeRequest> inComeRequests){
        //调用ai接口
        try{
            List<InComeResponse> inComeResponses = aiAnalysisClient.getIncome(inComeRequests);

            if(inComeResponses != null && !inComeResponses.isEmpty()){
                saveAnalysisIncome(inComeResponses);
            }
        }catch (Exception e){
            log.error("analysisIncome 调用ai接口识别收入 error ,msg:{}",e.getMessage());
        }
    }

    /**
     * 保存数据库
     * @param inComeResponses
     */
    public void saveAnalysisIncome(List<InComeResponse> inComeResponses){
        //更新数据库 blogger
        insBloggerDao.batchUpdateIncome(inComeResponses);
        //更新数据库 blogger_main
        insBloggerMainDao.batchUpdateIncome(inComeResponses);
    }

    /**
     * 发送优先统计收入的消息
     * @param insBloggerMessage
     */
    public void sendPriorityStMsg(InsBloggerMessage insBloggerMessage){
        insBloggerMessage.setTypeCode(InsBloggerMsgTypeCodeEnum.ST_INCOME.getCode());
        insBloggerMessage.setRetryTimes(insAnalysisConfig.getInsMBloggerActiveFollowerDataStPriorityRetryTimes());
        insBloggerMessage.setRetryLimitTimes(insAnalysisConfig.getInsMBloggerActiveFollowerDataStPriorityRetryTimes());
        insBloggerMessage.setEventTime(System.currentTimeMillis());
        kafkaTemplateInsAnalysisAvatar.send(insAnalysisConfig.getInsMBloggerActiveFollowerDataStPriorityTopic(),insBloggerMessage);
    }
}
